package com.fantuan.weixin;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fantuan.weixin.bean.InMessage;
import com.fantuan.weixin.bean.InMessageText;
import com.fantuan.weixin.bean.OutMessage;

@Controller
public class PortalAction {

	private static Log logger = LogFactory.getLog(PortalAction.class);
	
	@Autowired
	@Qualifier("messageProcessingHandlerImpl")
	private MessageProcessingHandler messageProcess;
	
	/**
	 * 验证开发模式可用
	 * @param request
	 * @param response
	 * @param groupid
	 * @return
	 * @throws SQLException
	 * @throws IOException 
	 */
	@RequestMapping("/wx.do")
	public void processMessage(
			HttpServletRequest request,
			HttpServletResponse response) throws SQLException, IOException
	{
		String method = request.getMethod();
		
		if( StringUtils.equalsIgnoreCase(method, "GET") )
		{
			/**
			 * 开发者模式验证逻辑
			 */
			String signature = request.getParameter( "signature" );
			String timestamp = request.getParameter( "timestamp" );
			String nonce = request.getParameter( "nonce" );
			String echostr = request.getParameter( "echostr" );

			if( StringUtils.isNotBlank(signature) && StringUtils.isNotBlank(timestamp)
					 && StringUtils.isNotBlank(nonce)
					 && StringUtils.isNotBlank(echostr))
			{
				IOUtils.write(echostr, response.getOutputStream());			
			}
			
			logger.debug("开发者模式校验完成");
		}
		else
		{
			response.setContentType("text/xml");

			//输入流
			ServletInputStream in = request.getInputStream();
			//转换为字符串
			String content = IOUtils.toString(in, CharEncoding.UTF_8);
			
			logger.debug("接收用户信息" + content);
			
			//实现处理接口
			InMessage inMessage = new InMessage( content );
			OutMessage outMessage = null;
			
			//文本消息
			if( StringUtils.equalsIgnoreCase(inMessage.getMsgType(),MessageProcessingHandler.MSG_TYPE_TEXT) )
			{
				InMessageText inMessageText = new InMessageText( content );
				outMessage = messageProcess.textTypeMsg(inMessageText);
			}
			
			//返回内容
			if( outMessage != null )
			{
				logger.debug("反馈用户：" + outMessage.toXML());
				IOUtils.write(outMessage.toXML(), response.getOutputStream());
			}
		}
	}	
}
